<template>
  <div class="add-dish-container">
    <el-dialog
      :title="isEdit?'修改菜品':'添加菜品'"
      :visible.sync="dialogVisible"
      width="600px"
      :before-close="dialogBeforeClose"
    >
      <el-form ref="dishData" :model="dishData" label-width="100px" :rules="rules">
        <el-form-item label="菜品名称" prop="name">
          <el-input v-model="dishData.name" placeholder="请输入菜品名称" />
        </el-form-item>
        <el-form-item label="菜品分类" prop="categoryId">
          <el-select v-model="dishData.categoryId" placeholder="请选择菜品分类">
            <el-option
              v-for="item in options"
              :key="item.id"
              :value-key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="菜品价格" prop="price">
          <el-input v-model="dishData.price" placeholder="请输入菜品价格" />
        </el-form-item>
        <el-form-item label="口味做法配置" prop="flavors">
          <div class="add-dish-container-flavors">
            <div>口味名（三个字内）口味标签（输入标签按下回车添加）</div>
            <div v-for="(flavor,indexD) in storeFlavors" :key="indexD" class="add-dish-container-flavors-input">
              <el-select
                v-model="flavor.name"
                style="width:120px;margin-right:30px"
                filterable
                allow-create
                default-first-option
                placeholder="请输入口味"
                @change="showFlavorsTag"
                @keydown="showFlavorsTag(true)"
              >
                <el-option
                  v-for="item in flavorSelectOption"
                  :key="item.name"
                  :value-key="item.children"
                  :label="item.name"
                  :value="[item,indexD]"
                />
              </el-select>
              <el-select
                ref="selectClose"
                v-model="flavor.value"
                multiple
                allow-create
                filterable
                :popper-append-to-body="false"
                default-first-option
                placeholder="请输入口味"
                popper-class="add-dish-container-flavors-select"
              />
              <el-link :underline="false" type="danger" @click="removeFlavor(indexD)">删除</el-link>
            </div>
            <el-button @click="addFlavors">添加口味</el-button>
          </div>
        </el-form-item>
        <el-form-item label="菜品图片" prop="image">
          <div>
            <el-upload
              ref="upload"
              class="upload-demo"
              action="/dev-api/common/upload"
              :auto-upload="false"
              :multiple="false"
              list-type="picture-card"
              :on-change="handleAvatarChange"
              :limit="1"
              :show-file-list="false"
              :on-remove="handleRemove"
              :on-success="uploadSuccess"
            >
              <img v-if="imageUrl" :src="imageUrl" class="avatar" :onerror="defaultImg">
            </el-upload>
          </div>
        </el-form-item>
        <el-form-item label="菜品描述" prop="description">
          <el-input v-model="dishData.description" type="textarea" placeholder="请输入菜品描述" :autosize="{minRows: 2, maxRows: 6}" resize="none" />
        </el-form-item>
      </el-form>
      <div />
      <div slot="footer">
        <el-button @click="dialogBeforeClose">取 消</el-button>
        <el-button type="primary" @click="submitData('dishData')">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getCategoryList, addDish, queryDishById, downloadImg, editDish } from '@/api/dish'
import { EventBus } from '@/utils/eventBus'
export default {
  name: 'AddDish',
  props: {
    show: {
      type: Boolean,
      require: true,
      default: true
    },
    isEdit: {
      type: Boolean,
      require: true,
      default: false
    },
    dishId: {
      type: String,
      require: false,
      default: ''
    }
  },
  data() {
    function validPrice(rule, value, callback) {
      if (!value) {
        callback(new Error('请输入价格'))
      }
      const price = parseFloat(value)
      if (isNaN(price)) {
        callback(new Error('价格只能为数字'))
      } else if (price < 0) {
        callback(new Error('价格不能为负数'))
      } else if (price > 10000) {
        callback(new Error('价格只能小于10000'))
      }
      callback()
    }
    return {
      dishData: {
        name: '',
        categoryId: '',
        price: '',
        flavors: [],
        image: '',
        status: 1,
        code: ''
      },
      flavors: [],
      name: '',
      storeFlavors: [],
      imageFileList: [],
      inputVisible: false,
      options: [],
      imageUrl: '',
      defaultImg: 'this.src="' + require('@/assets/defaultImg/noImg.png') + '"',
      flavorSelectOption: [
        { name: '甜度', children: ['无糖', '三分甜', '五分甜', '七分甜', '全糖'] },
        { name: '温度', children: ['正常冰', '少冰', '去冰', '常温', '温热', '热'] },
        { name: '忌口', children: ['不要葱', '不要香菜'] },
        { name: '辣度', children: ['不辣', '微辣', '特辣'] }
      ],
      rules: {
        name: [
          { required: true, message: '请输入菜品名称', trigger: 'blur' },
          { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }
        ],
        categoryId: [
          { required: true, message: '请选择菜品类型', trigger: 'blur' }
        ],
        price: { validator: validPrice, trigger: blur }
      }
    }
  },
  computed: {
    dialogVisible: {
      get() {
        return this.show
      },
      set(val) {
        this.$emit('update:show', val)
      }
    }
  },
  created() {
    if (this.isEdit) {
      this.getDishInformation()
    }
    this.getCategoryListOptions()
  },
  methods: {
    async getDishInformation() {
      const { data } = await queryDishById(this.dishId)
      console.log(data)

      this.dishData = data
      this.dishData.price /= 100
      const { flavors, image } = data
      flavors.forEach((flavor) => {
        const { name, value } = flavor
        const valueArr = JSON.parse(value)
        this.storeFlavors.push({ name, value: valueArr })
      })
      this.imageFileList = [{ name: image, url: downloadImg(image) }]
      this.imageUrl = downloadImg(image)
    },
    async getCategoryListOptions() {
      const { data } = await getCategoryList({ type: 1 })
      this.options = data || []
    },
    dialogBeforeClose() {
      Object.assign(this.$data, this.$options.data)
      this.dialogVisible = false
    },
    async submitData(formName) {
      this.$refs[formName].validate(async(valid) => {
        if (valid) {
          this.dishData.flavors = []
          console.log(this.dishData, this.storeFlavors)
          this.storeFlavors.forEach((flavor) => {
            const { name, value } = flavor
            const valueStr = JSON.stringify(value)
            this.dishData.flavors.push({ name, showOption: false, value: valueStr })
          })
          this.dishData.price *= 100
          if (this.isEdit) {
            const res = await editDish(this.dishData)
            if (res?.code) {
              this.$message.success('修改成功')
            }
          } else {
            const result = await addDish(this.dishData)
            if (result.code) {
              this.$message.success('新增成功')
            }
          }
          EventBus.$emit('retchDishData')
          this.dialogBeforeClose()
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    handleInputConfirm(index) {
      const { inputValue } = this.storeFlavors[index]
      if (inputValue) {
        this.storeFlavors[index].value.splice(this.storeFlavors[index].value.length, 0, inputValue)
      }
      this.storeFlavors[index].inputVisible = false
      this.storeFlavors[index].inputValue = ''
    },
    addFlavors() {
      this.storeFlavors.push({ name: '', value: [] })
    },
    handleRemove(file, fileList) {
      this.imageUrl = ''
    },
    handleAvatarChange(file, fileList) {
      this.$refs.upload.submit()
    },
    uploadSuccess(res) {
      const { data } = res
      this.dishData.image = data
      this.imageUrl = downloadImg(data)
    },
    beforeDestroy() {
      this.$refs.dishData.resetFields()
    },
    showFlavorsTag(flavorsArr) {
      if (typeof flavorsArr === 'string') {
        return
      }
      const index = flavorsArr[1]
      const { name, children } = flavorsArr[0]
      this.storeFlavors[index].value = children
      this.storeFlavors[index].name = name
    },
    removeFlavor(index) {
      this.storeFlavors.splice(index, 1)
    }
  }
}
</script>

<style lang="scss">
.add-dish-container{
  // .el-popper[x-placement^=bottom] {
  //     display: none;
  //   }

  &-flavors{
    .el-input__suffix{
      display: none !important;
    }
    .el-popper{
        display: none !important;
      }
    &-select{
      .el-select-dropdown__empty{
        display: none !important;
      }
      .el-popper{
        display: none !important;
        .el-select-dropdown{
          display: none !important;
        }
      }

    }
    .el-button{
      margin: 5px auto;
    }
    &-input{
      display: flex;
      margin-top: 10px;
      .el-select{
        margin-right: 20px;
      }
    }
  }
  &-upload{
    .el-upload{
      display: none;
      img{
        width: 100% !important;
        height: 100% !important;
      }
    }
  }
  img{
    width: 100% !important;
    height: 100% !important;
  }
  .el-select{
    display: block;
  }
}
</style>
